import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, message } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { getUsers, createUser, updateUser, deleteUser } from '../../services/api';

const { Option } = Select;

const UserConfig = () => {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(false);
  const [visible, setVisible] = useState(false);
  const [editMode, setEditMode] = useState(false);
  const [currentUser, setCurrentUser] = useState({});
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');

  useEffect(() => {
    fetchUsers();
  }, []);

  const fetchUsers = async () => {
    setLoading(true);
    try {
      const data = await getUsers();
      setUsers(data);
    } catch (error) {
      message.error('获取用户列表失败');
      console.error('Failed to fetch users:', error);
    }
    setLoading(false);
  };

  const handleAdd = () => {
    setEditMode(false);
    setCurrentUser({});
    form.resetFields();
    setVisible(true);
  };

  const handleEdit = (user) => {
    setEditMode(true);
    setCurrentUser(user);
    form.setFieldsValue(user);
    setVisible(true);
  };

  const handleDelete = async (id) => {
    try {
      await deleteUser(id);
      message.success('删除用户成功');
      fetchUsers();
    } catch (error) {
      message.error('删除用户失败');
      console.error('Failed to delete user:', error);
    }
  };

  const handleSubmit = async (values) => {
    try {
      if (editMode) {
        await updateUser(currentUser.id, values);
        message.success('更新用户成功');
      } else {
        await createUser(values);
        message.success('创建用户成功');
      }
      setVisible(false);
      fetchUsers();
    } catch (error) {
      message.error(editMode ? '更新用户失败' : '创建用户失败');
      console.error('Failed to submit user:', error);
    }
  };

  const filteredUsers = users.filter(user =>
    user.username.toLowerCase().includes(searchText.toLowerCase()) ||
    user.email.toLowerCase().includes(searchText.toLowerCase()) ||
    user.phone.includes(searchText)
  );

  const columns = [
    { title: 'ID', dataIndex: 'id', key: 'id' },
    { title: '用户名', dataIndex: 'username', key: 'username' },
    { title: '邮箱', dataIndex: 'email', key: 'email' },
    { title: '电话', dataIndex: 'phone', key: 'phone' },
    { title: '角色', dataIndex: 'role', key: 'role', render: role => <span>{role.name}</span> },
    { title: '部门', dataIndex: 'department', key: 'department', render: dept => <span>{dept?.name || '-'}</span> },
    { title: '状态', dataIndex: 'status', key: 'status', render: status => (
      <span style={{ color: status === 'active' ? 'green' : 'red' }}>
        {status === 'active' ? '启用' : '禁用'}
      </span>
    )},
    { title: '操作', key: 'action', render: (_, record) => (
      <div>
        <Button
          type="primary"
          icon={<EditOutlined />}
          size="small"
          style={{ marginRight: 8 }}
          onClick={() => handleEdit(record)}
        >
          编辑
        </Button>
        <Button
          type="danger"
          icon={<DeleteOutlined />}
          size="small"
          onClick={() => handleDelete(record.id)}
        >
          删除
        </Button>
      </div>
    )}
  ];

  return (
    <div className="user-config">
      <div className="header">
        <h2>用户配置</h2>
        <div className="search-bar">
          <Input
            placeholder="搜索用户名、邮箱或电话"
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
          />
          <Button type="primary" icon={<PlusOutlined />} onClick={handleAdd}>
            新增用户
          </Button>
        </div>
      </div>
      <Table
        columns={columns}
        dataSource={filteredUsers}
        loading={loading}
        rowKey="id"
        pagination={{ pageSize: 10 }}
      />

      <Modal
        title={editMode ? '编辑用户' : '新增用户'}
        visible={visible}
        onOk={form.submit}
        onCancel={() => setVisible(false)}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Form.Item
            name="username"
            label="用户名"
            rules={[{ required: true, message: '请输入用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            name="email"
            label="邮箱"
            rules={[
              { required: true, message: '请输入邮箱' },
              { type: 'email', message: '请输入有效的邮箱地址' }
            ]}
          >
            <Input placeholder="请输入邮箱" />
          </Form.Item>

          <Form.Item
            name="phone"
            label="电话"
            rules={[
              { required: true, message: '请输入电话' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号码' }
            ]}
          >
            <Input placeholder="请输入电话" />
          </Form.Item>

          <Form.Item name="roleId" label="角色" rules={[{ required: true, message: '请选择角色' }]}>
            <Select placeholder="请选择角色">
              {/* 这里需要动态加载角色数据 */}
              <Option value={1}>管理员</Option>
              <Option value={2}>普通用户</Option>
              <Option value={3}>访客</Option>
            </Select>
          </Form.Item>

          <Form.Item name="departmentId" label="部门">
            <Select placeholder="请选择部门">
              {/* 这里需要动态加载部门数据 */}
              <Option value={1}>技术部</Option>
              <Option value={2}>市场部</Option>
              <Option value={3}>财务部</Option>
            </Select>
          </Form.Item>

          <Form.Item name="status" label="状态" rules={[{ required: true, message: '请选择状态' }]}>
            <Select placeholder="请选择状态">
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default UserConfig;